#include "atcommand.h"
#include "driver_uart.h"
#include <stdio.h>
#include <string.h>
#include "esp8266_device.h"

int ATCommandSend(char *cmd, char *target, int iTimeoutMS)
{
    char *buf = target;
    memset(target, 0, INFOSIZE);
    int i = 0;
    int pre;
	int now;
    USART3_RingbufferInit();
    USART3_SendBytes(cmd, strlen(cmd));
    
  	pre = HAL_GetTick();
    
    while(iTimeoutMS)
	{
        if(USART3_ReadBytes(&buf[i]) == PDSUCCESS)
		{
            if ((i != 0) && (buf[i-1] == '\r') && (buf[i] == '\n'))
			{
                if(strstr(buf, "OK\r\n") != NULL)
				{
//                    printf("OK\r\n");
					return PDSUCCESS;
				}
				else if(strstr(buf, "ERROR\r\n") != NULL)
				{
//                    printf("ERROR\r\n");
					return PDFAIL;
				}
			}
			i++;       
		 }

      	now = HAL_GetTick();
		if (now > pre)
		{
            iTimeoutMS--;
			pre = now;
		}		  
    }
//    printf("timeout1\r\n");
	return PDTIMEOUT;  
}


int ATDataRecv(char *data, int *pLen, int iTimeoutMS)
{
    char buf[100] = {0};
    int len = 0;
    int i = 0;
    int cnt = 0;
    int pre;
	int now;
    
    RECV_STATUS  recvStatus = INIT_STATUS;

  	pre = HAL_GetTick();

    while(iTimeoutMS)
    {
        if(USART3_ReadBytes(&buf[i]) == PDSUCCESS)
        {
            switch(recvStatus)
            {
                case INIT_STATUS:
                {
                    buf[i+1] = '\0';
                    if(strstr(buf, "+IPD,") != NULL)
                    {
                        recvStatus = LENGTH_STATUS;
                        i = 0;
                    }else{
                        i++;
                    }
                    break;
                }
                case LENGTH_STATUS:
                {
                    if(buf[i] == ':')
                    {
                        for(cnt=0; cnt<i; cnt++)
                        {
                            len = len*10 + buf[cnt] - '0';
                        }
                            recvStatus = DATA_STATUS;                         
                            i = 0;      
                        
                    }else{
                        i++;
                    }
                    break;
                }
                case DATA_STATUS:
                {
                    data[i] = buf[i];
                    i++;
                    if(i == len)
                    {
                        if(pLen)
                        {
                            *pLen = len;
                        }
                          return PDSUCCESS;
                    }   
                    break;
                } 
            } 
            
        }
        now = HAL_GetTick();
		if (now > pre)
		{
			iTimeoutMS--;
			pre = now;
		}        
    }
       return PDTIMEOUT;     
}

